package dawn.core.dispatch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 默认的调度器，继承此类实现调度功能
 * @author huangxiao
 */
public class DefaultDispatcher implements IDispatcher<Integer, Event> {

	Map<Integer, List<Invoker<Event>>> listenerMap = new HashMap<Integer, List<Invoker<Event>>>();

	Map<Integer, List<IFilter>> filterMap = new HashMap<Integer, List<IFilter>>();

	@Override
	public void dispatch(Integer type, Event event) {

		// for
		List<IFilter> filters = filterMap.get(type);
		if (filters != null) {
			for (IFilter filter : filters) {
				filter.before(null, null, null);
			}
		}
		
		List<Invoker<Event>> listeners = listenerMap.get(type);
		if (listeners != null) {
			for (Invoker<Event> listener : listeners) {

				try {
					listener.handle(event);
				} catch (Exception e) {
					if (filters != null) {
						for (IFilter filter : filters) {
							filter.error(null, null, null);
						}
					}
					e.printStackTrace();
					continue;
				}
			}
		}
		
		if (filters != null) {
			for (IFilter filter : filters) {
				filter.after(null, null, null, null);
			}

		}

	}

	@Override
	public void addListener(Integer type, Invoker<Event> listener) {
		List<Invoker<Event>> list = listenerMap.get(type);
		if (list == null) {
			list = new ArrayList<Invoker<Event>>();
			listenerMap.put(type, list);
		}
		list.add(listener);

	}

	@Override
	public void addFilter(Integer type, IFilter filter) {
		List<IFilter> list = filterMap.get(type);
		if (list == null) {
			list = new ArrayList<IFilter>();
			filterMap.put(type, list);
		}
		list.add(filter);
	}

}
